<template>
    <div class="bigBox">
        <div class="box">
            <!-- 滑动盒子 -->
            <div class="pre-box" :style="{ backgroundColor: preBoxColor, transform: preBoxTransform }">
                <h1>WELCOME</h1>
                <p>JOIN US!</p>
                <div class="img-box">
                    <img :src="imgSrc" alt="图片未成功加载" />
                </div>
            </div>

            <!-- 注册盒子 -->
            <div class="register-form">
                <div class="title-box">
                    <h1>注册</h1>
                </div>
                <el-form ref="registerFormRef" :model="registerForm" :rules="rules">
                    <el-form-item prop="username" label=" ">
                        <el-input type="text" placeholder="用户名" :suffix-icon="User" v-model="registerForm.username" />
                    </el-form-item>
                    <el-form-item prop="password" label=" ">
                        <el-input type="password" placeholder="密码" :suffix-icon="Lock"
                            v-model="registerForm.password" />
                    </el-form-item>
                    <el-form-item prop="confirmpassword" label=" ">
                        <el-input type="password" placeholder="确认密码" :suffix-icon="Lock"
                            v-model="registerForm.confirmpassword" />
                    </el-form-item>
                </el-form>
                <div class="btn-box">
                    <button @click="handleRegister">注册</button>
                    <p @click="mySwitch">已有账号? 去登录</p>
                </div>
            </div>

            <!-- 登录盒子 -->
            <div class="login-form">
                <div class="title-box">
                    <h1>登录</h1>
                </div>
                <el-form ref="loginFormRef" :model="loginForm" :rules="rules">
                    <el-form-item prop="username" label=" ">
                        <el-input type="text" placeholder="用户名" :suffix-icon="User" v-model="loginForm.username" />
                    </el-form-item>
                    <el-form-item prop="password" label=" ">
                        <el-input type="password" placeholder="密码" :suffix-icon="Lock" v-model="loginForm.password" />
                    </el-form-item>
                    <el-form-item label=" ">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <el-input v-model="userCaptcha" placeholder="请输入验证码" maxlength="6" style="flex: 1;" />
                            <img :src="captchaImg" alt="验证码" title="点击更换" class="captcha-img" @click="refreshCaptcha"
                                style="height: 36px; border-radius: 4px; cursor: pointer;" />
                        </div>
                    </el-form-item>
                </el-form>
                <div class="btn-box">
                    <button @click="handleLogin">登录</button>
                    <p @click="mySwitch">没有账号? 去注册</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import SuperMario from '@/assets/img_login/SuperMario1.jpg'
import Contra from '@/assets/img_login/Contra.jpg'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const flag = ref(true)
const imgSrc = ref(SuperMario)
const preBoxColor = ref('#ac0808')
const preBoxTransform = ref('translateX(0%)')

// 自动导入验证码图
const captchaMap = Object.fromEntries(
    Object.entries(
        import.meta.glob('@/assets/img_login/captcha/*.png', { eager: true, import: 'default' })
    ).map(([path, module]) => {
        const name = path.split('/').pop().replace('.png', '')
        return [name, module]
    })
)
const captchaList = Object.keys(captchaMap)
const captchaCode = ref('')
const captchaImg = ref('')
const userCaptcha = ref('')

function refreshCaptcha() {
    const pick = captchaList[Math.floor(Math.random() * captchaList.length)]
    captchaCode.value = pick
    captchaImg.value = captchaMap[pick]
}

onMounted(() => {
    refreshCaptcha()
    setInterval(createBubble, 200)
})

const loginForm = reactive({
    username: '',
    password: ''
})

const registerForm = reactive({
    username: '',
    password: '',
    confirmpassword: ''
})

const loginFormRef = ref('')
const registerFormRef = ref('')
const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 5, message: '长度应该在3~5个字符之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '长度应大于6', trigger: 'blur' },
    ],
    confirmpassword: [
        { required: true, message: '请输入相同的密码', trigger: 'blur' },
        { min: 6, message: '长度应大于6', trigger: 'blur' },
    ],
})

function mySwitch() {
    flag.value = !flag.value
    if (flag.value) {
        preBoxTransform.value = 'translateX(0%)'
        preBoxColor.value = '#ac0808'
        imgSrc.value = SuperMario
    } else {
        preBoxTransform.value = 'translateX(100%)'
        preBoxColor.value = '#1173a8'
        imgSrc.value = Contra
    }
}

function handleLogin() {
    if (userCaptcha.value.trim().toUpperCase() !== captchaCode.value) {
        alert('验证码错误，请重新输入')
        refreshCaptcha()
        return
    }
    fetch('http://localhost:5000/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(loginForm),
        credentials: 'include'
    })
        .then(res => res.json())
        .then(data => {
            if (data.message === '登录成功') {
                import('@/store/user').then(({ useUserStore }) => {
                    const userStore = useUserStore()
                    fetch('http://localhost:5000/me', {
                        credentials: 'include'
                    })
                        .then(res => res.json())
                        .then(meData => {
                            if (meData.status === 'success') {
                                userStore.setAvatar(meData.data.avatar)
                                if (meData.data.manage) {
                                    window.location.href = '/manage'
                                } else {
                                    window.location.href = '/'
                                }
                            }
                        })
                        .catch(err => {
                            console.error('获取用户信息失败:', err)
                            window.location.href = '/'
                        })
                })
            } else {
                alert(data.message || '登录失败')
            }
        })
        .catch(err => {
            console.error('登录请求失败:', err)
            alert('网络错误，请稍后再试')
        })
}

function handleRegister() {
    if (registerForm.password !== registerForm.confirmpassword) {
        alert('两次输入的密码不一致');
        return;
    }
    fetch('http://localhost:5000/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            username: registerForm.username,
            password: registerForm.password
        })
    })
        .then(res => res.json())
        .then(data => {
            alert(data.message);
        })
        .catch(err => {
            console.error('注册请求失败:', err);
            alert('网络错误，请稍后再试');
        });
}

function createBubble() {
    const bubble = document.createElement('span')
    const r = Math.random() * 5 + 25
    bubble.style.width = `${r}px`
    bubble.style.height = `${r}px`
    bubble.style.left = `${Math.random() * window.innerWidth}px`
    bubble.className = 'bubble'
    document.body.appendChild(bubble)
    setTimeout(() => bubble.remove(), 4000)
}
</script>



<style scoped>
input {
    outline: none;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.bigBox {
    height: 100vh;
    width: 100vw;
    overflow-x: hidden;
    display: flex;
    background: linear-gradient(to right, rgb(230, 21, 52), rgb(191, 227, 241));
}

.box {
    flex: 1;
    height: 600px;
    display: flex;
    position: relative;
    z-index: 2;
    margin: auto;
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.6);
    box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
    max-width: 1200px;
}

.pre-box {
    width: 50%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 99;
    border-radius: 4px;
    background-color: #ac0808;
    box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
    transition: 0.5s ease-in-out;
}

.pre-box h1 {
    margin-top: 150px;
    text-align: center;
    letter-spacing: 5px;
    color: white;
    user-select: none;
    text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
}

.pre-box p {
    height: 30px;
    line-height: 30px;
    text-align: center;
    margin: 20px 0;
    user-select: none;
    font-weight: bold;
    color: white;
    text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
}

.img-box {
    width: 200px;
    height: 200px;
    margin: 20px auto;
    border-radius: 50%;
    user-select: none;
    overflow: hidden;
    box-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
}

.img-box img {
    width: 100%;
    transition: 0.5s;
}


.login-form .title-box {
    height: auto;
    line-height: normal;
    margin-top: 260px;
    margin-bottom: 20px;
    /* ✅ 留一点空间 */
    text-align: center;
}

.register-form .title-box {
    height: auto;
    line-height: normal;
    margin-top: 200px;
    margin-bottom: 20px;
    /* ✅ 留一点空间 */
    text-align: center;
}

.login-form,
.register-form {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
}


.title-box h1 {
    text-align: center;
    color: white;
    user-select: none;
    letter-spacing: 5px;
    text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
}

.el-form {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.el-form-item {
    width: 65%;
}

input {
    /* width: 60%; */
    height: 40px;
    margin-bottom: 20px;
    text-indent: 10px;
    border: 1px solid #fff;
    background-color: rgba(255, 255, 255, 0.3);
    border-radius: 120px;
    backdrop-filter: blur(10px);
}

input:focus {
    color: #b0cfe9;
}

input:focus::placeholder {
    opacity: 0;
}

.btn-box {
    display: flex;
    justify-content: center;
}

button {
    width: 100px;
    height: 30px;
    margin: 0 7px;
    line-height: 30px;
    border: none;
    border-radius: 4px;
    background-color: #69b3f0;
    color: white;
}

button:hover {
    cursor: pointer;
    opacity: 0.8;
}

.btn-box p {
    height: 30px;
    line-height: 30px;
    user-select: none;
    font-size: 14px;
    color: white;
}

.btn-box p:hover {
    cursor: pointer;
    border-bottom: 1px solid white;
}

.bubble {
    position: absolute;
    z-index: 0;
    bottom: 0;
    border-radius: 50%;
    background: radial-gradient(circle at 72% 28%, #fff 3px, #ff7edf 8%, #5b5b5b, #aad7f9 100%);
    box-shadow: inset 0 0 6px #fff, inset 3px 0 6px #eaf5fc, inset 2px -2px 10px #efcde6,
        inset 0 0 60px #f9f6de, 0 0 20px #fff;
    animation: myMove 4s linear infinite;
}

@keyframes myMove {
    0% {
        transform: translateY(0%);
        opacity: 1;
    }

    50% {
        transform: translate(10%, -1000%);
    }

    75% {
        transform: translate(-20%, -1200%);
    }

    99% {
        opacity: 0.9;
    }

    100% {
        transform: translateY(-1800%) scale(1.5);
        opacity: 0;
    }
}
</style>

<!-- 全局修复 style.css 限制 -->
<style>
body.layout-login #app {
max-width: none;
padding: 0;
margin: 0;
}
</style>
